import os
import subprocess
import platform


def find_disk():
    if platform.system() == 'Linux':
        mount_point = "/mnt/peinjector_mount_point"
        if not os.path.exists(mount_point):
            os.mkdir(mount_point)
        elif len(os.listdir(mount_point)):
            raise OSError(f"Mount point {mount_point} not empty!")

        i: int = 97
        while os.path.exists(f"/dev/sd{chr(i)}"):
            j: int = 1
            while os.path.exists(f"/dev/sd{chr(i)}{str(j)}"):
                subprocess.call(f"sudo mount /dev/sd{chr(i)}{str(j)} {mount_point}",shell=True)
                if os.path.exists(mount_point+"/PEinjector"):
                    return mount_point
                j += 1
                subprocess.call(f"sudo umount {mount_point}",shell=True)
            i += 1

        i: int = 0
        while os.path.exists(f"/dev/nvme{str(i)}"):
            j: int = 1
            while os.path.exists(f"/dev/nvme{str(i)}n{str(j)}"):
                k: int = 1
                while os.path.exists(f"/dev/nvme{str(i)}n{str(j)}p{str(k)}"):
                    subprocess.call(
                        f"sudo mount /dev/nvme{str(i)}n{str(j)}p{str(k)} {mount_point} --mkdir",
                        shell=True
                    )
                    if os.path.exists(mount_point+"/PEinjector"):
                        return mount_point
                    k += 1
                    subprocess.call(f"sudo umount {mount_point}",shell=True)
                j += 1
            i += 1

    elif platform.system() == 'Windows':
        for i in "CDEFGHIJKABLMNOPQRSTUVWYZ":
            this_disk = i+":"
            if os.path.exists(this_disk + "/PEinjector"):
                return this_disk

    else:
        raise OSError(f"Unsupported operating system:{platform.system()}")
    raise OSError(
        "Cannot find the PEinjector disk!")


def get_builtin_dir(path: str = "") -> str:
    root_path = '/'.join(os.path.dirname(__file__).replace("\\",
                         "/").split("/")[:-1])
    if path == "":
        return root_path
    return root_path+"/"+path
